package com.example.onenetdht11;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.example.onenetdht11.util.ChartUtils;
import com.example.onenetdht11.util.OneNetUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class EditFragment extends Fragment implements DatePicker.OnDateChangedListener{
    View view;
    LineChart chart;
    ChartUtils chartUtils;
    TextView tvstart,tvend;
    List<Entry> list = new ArrayList<>();
    OneNetUtils oneNetUtils = null;
    MainActivity ma;
    Spinner spstreams;
    CheckBox cbtime;
    LinearLayout llstart,llend;
    StringBuffer startdate,enddate;
    int startyear,startmouth,startday;
    int endyear,endmouth,endday;
    String start,end;
    Button btnedit;
    String count = "0";
    public EditFragment(){

    }
    public EditFragment(MainActivity mainActivity){
        this.ma = mainActivity;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_edit,container,false);//第一个参数是布局文件名，第二个是父容器
        startdate = new StringBuffer();
        enddate = new StringBuffer();
        initView();
        initData();
        initListener();
        initChart();
        initTimeData();
        return view;
    }

    void initView(){
        chart = view.findViewById(R.id.chart);

        llstart = view.findViewById(R.id.start_date);
        llend = view.findViewById(R.id.end_date);
        tvend = view.findViewById(R.id.tv_end_date);
        tvstart = view.findViewById(R.id.tv_start_date);
        spstreams = view.findViewById(R.id.sp_streams);
        cbtime = view.findViewById(R.id.cb_time);
        btnedit = view.findViewById(R.id.btn_edit);
        //chart.initChart(chart);
    }
    void initChart(){
/*        LineDataSet one = new LineDataSet(list, "One");
        LineData lineData  = new LineData();
        lineData.addDataSet(one);
        chart.setData(lineData);
        chart.invalidate();*/
    }

    String[] spData = {"室内温度","室内湿度","室内烟雾浓度","室外声音强度"};

    void initData(){

        ArrayAdapter<String> adapter =new ArrayAdapter<>(ma,
                android.R.layout.simple_spinner_dropdown_item, spData);
        spstreams.setAdapter(adapter);
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        this.startyear = year;
        this.startmouth = monthOfYear;
        this.startday = dayOfMonth;
        this.endyear = year;
        this.endmouth = monthOfYear;
        this.endday = dayOfMonth;
    }

    class CalendarListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            if (view.getId() == R.id.start_date){
                startPick();
            }else if (view.getId() == R.id.end_date){
                endPick();
            }
        }
    }

    private void endPick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ma);
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String m,d;
                if (enddate.length()> 0 ){
                    enddate.delete(0,enddate.length());
                }
                if (endmouth <10){
                    m = "0" + String.valueOf(endmouth+1);
                }else {
                    m = String.valueOf(endmouth+1);
                }
                if (endday < 10){
                    d = "0" + String.valueOf(endday);
                }else {
                    d = String.valueOf(endday);
                }
                tvend.setText(enddate.append(String.valueOf(endyear)).append("-").append(m)
                        .append("-").append(d));
                dialogInterface.dismiss();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(ma,R.layout.dialog_date,null);
        final DatePicker datePicker = dialogView.findViewById(R.id.datepicker);

        dialog.setTitle("终止日期");
        dialog.setView(dialogView);
        dialog.show();
        datePicker.init(endyear, endmouth, endday,this);
    }

    void initTimeData(){
        Calendar calendar = Calendar.getInstance();
        startyear = calendar.get(Calendar.YEAR);
        startmouth = calendar.get(Calendar.MONTH);
        startday = calendar.get(Calendar.DAY_OF_MONTH);
        endyear = calendar.get(Calendar.YEAR);
        endmouth = calendar.get(Calendar.MONTH);
        endday = calendar.get(Calendar.DAY_OF_MONTH);
    }
    private void startPick() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ma);
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String m,d;
                if (startdate.length()> 0 ){
                    startdate.delete(0,startdate.length());
                }
                if (startmouth <10){
                    m = "0" + String.valueOf(startmouth+1);
                }else {
                    m = String.valueOf(startmouth+1);
                }
                if (startday < 10){
                    d = "0" + String.valueOf(startday);
                }else {
                    d = String.valueOf(startday);
                }
                tvstart.setText(startdate.append(String.valueOf(startyear)).append("-").append(m)
                        .append("-").append(d));
                dialogInterface.dismiss();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(ma,R.layout.dialog_date,null);
        final DatePicker datePicker = dialogView.findViewById(R.id.datepicker);

        dialog.setTitle("起始日期");
        dialog.setView(dialogView);
        dialog.show();

        datePicker.init(startyear,startmouth,startday,this);
    }

    void initListener(){
        CalendarListener calendarListener = new CalendarListener();
        AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String streamsStatic = parent.getItemAtPosition(position).toString();
                switch (streamsStatic) {
                    case "室内温度":
                        Contests.DataStream = Contests.WDStream;
                        break;
                    case "室内湿度":
                        Contests.DataStream = Contests.SDStream;
                        break;
                    case "室内烟雾浓度":
                        Contests.DataStream = Contests.MQStream;
                        break;
                    case "室外声音强度":
                        Contests.DataStream = Contests.SoundStream;
                        break;
                }
                downloadtime();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                downloadtime();

            }
        };

        llend.setOnClickListener(calendarListener);
        llstart.setOnClickListener(calendarListener);
        spstreams.setOnItemSelectedListener(onItemSelectedListener);

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                      downloadtime();
            }
        };
        btnedit.setOnClickListener(listener);
    }

    Runnable getchartData = new Runnable() {

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void run() {
            try {
                oneNetUtils = new OneNetUtils(ma);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
            list.clear();
            ArrayList<String> array = new ArrayList<String>();
            Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH);
            int d=cal.get(Calendar.DATE);
            String mouth,day;
            if (m <10){
                mouth  = "0" + String.valueOf(m+1);
            }else {
                mouth = String.valueOf(m+1);
            }
            if (d < 10){
                day = "0" + String.valueOf(d);
            }else {
                day = String.valueOf(d);
            }
            String newtime = y + "-" + mouth +"-" + day + "T00:00:00";
            array = oneNetUtils.getInfo(Contests.DataStream,newtime);
            if (array == null){
                chart.setData(null);
                chart.setNoDataText("今日暂无数据,请先使用设备采集数据");
                chart.invalidate();
            }else {
                for (int i = 0; i < array.size(); i += 5) {
                    list.add(new Entry(i, Float.parseFloat(array.get(i))));
                    ma.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (Contests.DataStream.equals(Contests.WDStream)) {
                                chart = chartUtils.initChart(chart, 50, -30);
                            } else if (Contests.DataStream == Contests.SDStream) {
                                chart = chartUtils.initChart(chart, 100, 0);
                            } else if (Contests.DataStream == Contests.MQStream) {
                                chart = chartUtils.initChart(chart, 50, 0);
                            } else if (Contests.DataStream == Contests.SoundStream) {
                                chart = chartUtils.initChart(chart, 50, 0);
                            }
                            chart.setScaleMinima(1.0f, 1.0f);
                            chart.getViewPortHandler().refresh(new Matrix(), chart, true);
                            LineDataSet one = new LineDataSet(list, "One");
                            LineData lineData = new LineData();
                            lineData.addDataSet(one);
                            chart.setNoDataText("今日暂无数据");
                            chart.setData(lineData);
                            chart.invalidate();
                        }
                    });
                }
            }
        }
    };
    Runnable getchartDatatime = new Runnable() {

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void run() {
            try {
                oneNetUtils = new OneNetUtils(ma);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            }
            list.clear();
            ArrayList<String> array = new ArrayList<String>();
            array = oneNetUtils.getInfo(Contests.DataStream,start,end);
            if (array == null){
                chart.setData(null);
                chart.setNoDataText("今日暂无数据,请先使用设备采集数据");
                chart.invalidate();
            }else {
                for (int i = 0; i < array.size(); i += 10) {
                    list.add(new Entry(i, Float.parseFloat(array.get(i))));
//                    list.add(new Entry(i, Float.valueOf(array.get(i)).floatValue()));
                    ma.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (Contests.DataStream.equals(Contests.WDStream)) {
                                chart = chartUtils.initChart(chart, 50, -30);
                            } else if (Contests.DataStream == Contests.SDStream) {
                                chart = chartUtils.initChart(chart, 100, 0);
                            } else if (Contests.DataStream == Contests.MQStream) {
                                chart = chartUtils.initChart(chart, 50, 0);
                            }
                            else if (Contests.DataStream == Contests.SoundStream) {
                                chart = chartUtils.initChart(chart, 50, 0);
                            }
                            chart.setScaleMinima(1.0f, 1.0f);
                            chart.getViewPortHandler().refresh(new Matrix(), chart, true);
                            LineDataSet one = new LineDataSet(list, "One");
                            LineData lineData = new LineData();
                            lineData.addDataSet(one);
                            chart.setData(lineData);
                            chart.invalidate();
                        }
                    });
                }
            }
        }
    };
    void downloadtime(){
        if (cbtime.isChecked()){
            String s = tvstart.getText().toString();
            String e = tvend.getText().toString();
            start = s + "T00:00:00";
            end = e + "T00:00:00";
            System.out.println(start  + "and" + end);
            new Thread(getchartDatatime).start();
        }else {
            new Thread(getchartData).start();
        }
    }

}
